package com.weirdor.bootmybatis.admin.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Component
@Aspect
public class LogAspect {

    private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("execution(public * com.weirdor.bootmybatis.admin.controller.*.*(..)))")
    public void logPointCut() {

    }

    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 记录下请求内容
        LOG.info("请求地址 : " + request.getRequestURI().toString());
        LOG.info("HTTP METHOD : " + request.getMethod());
        LOG.info("IP : " + request.getRemoteAddr());
        LOG.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
                + joinPoint.getSignature().getName());
        LOG.info("参数 : " + Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "ret"
            , pointcut = "logPointCut()")
    public void log(Object ret) {
        LOG.info("返回值 : " + ret);
    }

    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint pjp) {
        long startTime = System.currentTimeMillis();
        Object ob = null;
        try {
            ob = pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        LOG.info("耗时 : " + (System.currentTimeMillis() - startTime));
        return ob;
    }

}
